package com.artron.mediaartron.ui.fragment.order;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Switch;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.Address;
import com.artron.mediaartron.data.entity.AddressData;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.net.api.OrderAddressApi;
import com.artron.mediaartron.data.task.AddressTask;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.widget.AddAddressItem;
import com.artron.mediaartron.util.RegexUtils;
import com.bigkoo.pickerview.OptionsPickerView;

import java.util.List;

import butterknife.BindView;
import rx.functions.Action1;


/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-23.
 */

public class OrderAddAddressFragment extends BaseStaticFragment implements View.OnClickListener {

    private static final String TAG = "OrderAddAddressFragment";

    @BindView(R.id.OrderAddAddressFragment_aai_receiver)
    protected AddAddressItem mAaiReceiver;
    @BindView(R.id.OrderAddAddressFragment_aai_contact)
    protected AddAddressItem mAaiContact;
    @BindView(R.id.OrderAddAddressFragment_aai_address)
    protected AddAddressItem mAaiAddress;
    @BindView(R.id.OrderAddAddressFragment_aai_detail)
    protected AddAddressItem mAaiDetail;
    @BindView(R.id.OrderAddAddressFragment_switch)
    protected Switch mSwitch;
    private Address mAddress;
    private int[] mPositionArr;
    private AddressData mAddressData;
    private OptionsPickerView mPvOptions;

    public static OrderAddAddressFragment newInstance(AddressData data) {
        OrderAddAddressFragment fragment = new OrderAddAddressFragment();
        fragment.init(data);
        return fragment;
    }

    private void init(AddressData data) {
        this.mAddressData = data;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_order_add_address;
    }

    @Override
    protected void initView() {
        if (mAddressData != null) {
            mAaiReceiver.setText(mAddressData.getName());
            mAaiContact.setText(mAddressData.getMobileCode());
            mAaiAddress.setText(String.format("%s-%s-%s", mAddressData.getProvinceName(),
                    mAddressData.getCityName(), mAddressData.getDistrictName()));
            mAaiDetail.setText(mAddressData.getDetail());
            mSwitch.setChecked("Y".equals(mAddressData.getIsDefault()));
        }

        mAaiContact.setInputType(InputType.TYPE_CLASS_PHONE);
        mAaiAddress.setOnClickListener(this);

        AddressTask.getAddress(mContext, new Action1<Address>() {
            @Override
            public void call(Address address) {
                mAddress = address;
                initAddressPicker();
            }
        });
    }

    private void initAddressPicker() {
        final List<Address.Province> provinces = AddressTask.getProvinces(mAddress);
        final List<List<Address.City>> cities = AddressTask.getCities(provinces);
        final List<List<List<Address.District>>> districts = AddressTask.getDistricts(provinces);

        //返回的分别是三个级别的选中位置
        mPvOptions = new  OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3 ,View v) {
                //返回的分别是三个级别的选中位置
                mPositionArr = new int[]{options1, options2, options3};

                String tx = provinces.get(options1).getPickerViewText() + "-" +
                        cities.get(options1).get(options2).getPickerViewText() +  "-" +
                        districts.get(options1).get(options2).get(options3).getPickerViewText();

                mAaiAddress.setText(tx);
            }
        })
                .setTitleText("城市选择")
                .build();
        mPvOptions.setPicker(provinces, cities, districts);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_save) {
            String receiver = mAaiReceiver.getText();
            String phoneNum = mAaiContact.getText();
            String detail = mAaiDetail.getText();
            String checkText = mSwitch.isChecked() ? "Y" : "N";

            if (!RegexUtils.isTelPhoneNum(phoneNum)) {
                ToastUtil.show("手机号格式错误");
                return super.onOptionsItemSelected(item);
            }

            if (TextUtils.isEmpty(receiver) ||
                    TextUtils.isEmpty(detail) ||
                    (mAddressData == null && mPositionArr == null)) {
                ToastUtil.show("请补充完整资料");
                return super.onOptionsItemSelected(item);
            }

            boolean isUpdate = true;
            if (mAddressData == null) {
                mAddressData = new AddressData();
                isUpdate = false;
            }

            mAddressData.setName(receiver);
            mAddressData.setMobileCode(phoneNum);
            mAddressData.setIsDefault(checkText);
            mAddressData.setDetail(detail);

            try {
                Address.Province province = mAddress.getProvinces().get(mPositionArr[0]);
                int provinceId = province.getPid();
                Address.City city = province.getCityList().get(mPositionArr[1]);
                int cityId = city.getPid();
                Address.District district = city.getDistricts().get(mPositionArr[2]);
                int districtId = district.getPid();
                mAddressData.setProvinceName(province.getName());
                mAddressData.setProvinceId(provinceId);
                mAddressData.setCityName(city.getName());
                mAddressData.setCityId(cityId);
                mAddressData.setDistrictName(district.getName());
                mAddressData.setDistrictId(districtId);
            } catch (Exception e) {

            }

            String passId = AppProfile.getUserInfo().getPassId();
            OrderAddressApi api = RetrofitHelper.getOrderAddressApi();
            if (isUpdate) {
                RetrofitHelper.subscript(api.updateAddress(mAddressData.getId(), passId, receiver,
                        phoneNum, mAddressData.getProvinceId(), mAddressData.getCityId(),
                        mAddressData.getDistrictId(), detail, checkText), mAction);
            } else {
                RetrofitHelper.subscript(api.saveAddress(passId, receiver, phoneNum,
                        mAddressData.getProvinceId(), mAddressData.getCityId(),
                        mAddressData.getDistrictId(), detail, checkText),mAction);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private Action1<Response> mAction = new Action1<Response>() {
        @Override
        public void call(Response response) {
            if (response != null && "1".equals(response.getStatus())) {
                if (response.getData() != null) {
                    String id = response.getData().toString();
                    if (TextUtils.isEmpty(mAddressData.getId())) {
                        mAddressData.setId(id);
                    }
                }
                onBackResult();
            }
        }

        private void onBackResult() {
            Intent intent = new Intent();
            intent.putExtra(GeneralActivity.CONTENT, mAddressData);
            getActivity().setResult(GeneralActivity.RESULT_OK, intent);
            ((Activity) mContext).onBackPressed();
        }
    };

    @Override
    public void onClick(View v) {
        //隐藏软键盘
        UIUtils.hiddenKeyboard(getView());

        if (mPvOptions != null) {
            mPvOptions.show();
        }
    }
}
